import Icon, {
  AudioMutedOutlined,
  AudioOutlined,
  DownOutlined,
  EditOutlined,
  MessageOutlined,
  UsergroupAddOutlined,
  VideoCameraAddOutlined,
  VideoCameraOutlined,
} from '@ant-design/icons';

import { recordIcon } from '@/components/Icons/svg';
import { useSearchParams } from '@@/exports';
import { useGetState } from 'ahooks';
import { Button, Dropdown } from 'antd';
import { useEffect, useState } from 'react';
import styles from './shareOperationBar.less';

let dropdownFlag = true;
const ShareOperationBar = () => {
  const [searchParams] = useSearchParams();
  const [volumeListTmp] = searchParams.getAll('volumeList');
  const [volumeFlagTmp] = searchParams.getAll('volumeFlag');
  const [cameraListTmp] = searchParams.getAll('cameraList');
  const [cameraFlagTmp] = searchParams.getAll('cameraFlag');
  const [meetingCodeTmp] = searchParams.getAll('meetingCode');
  const volumeList = JSON.parse(volumeListTmp);
  const [volumeFlag, setVolumeFlag, getVolumeFlag] = useGetState<boolean>(
    JSON.parse(volumeFlagTmp),
  );
  const cameraList = JSON.parse(cameraListTmp);
  const [cameraFlag, setCameraFlag, getCameraFlag] = useGetState<boolean>(
    JSON.parse(cameraFlagTmp),
  );
  const meetingCode = parseInt(meetingCodeTmp);
  const [time, setTime] = useState({ hours: 0, minutes: 0, seconds: 0 });
  const [barHidden, setBarHidden] = useState<boolean>(false);
  const userInfo = JSON.parse(localStorage.getItem('userInfo')!);
  const [streamType, setStreamType, getStreamType] = useGetState<string>('');
  const [recordFlag, setRecordFlag, getRecordFlag] =
    useGetState<boolean>(false);

  useEffect(() => {
    const [streamTypeTmp] = searchParams.getAll('streamTypeTmp');
    console.log('streamTypeTmp', streamTypeTmp);
    setStreamType(streamTypeTmp);
    let barHiddenSwitch;

    setTimeout(() => {
      setBarHidden(true);
    }, 5000);

    //回调主进程显示窗体
    window.tm!.ipcRenderer.send('set-shareOperationBarWindow-show');
    const el = document.getElementById('barShowId');
    const barSwitch = document.getElementById('barSwitchId');
    const handleMouseEnter = () => {
      console.log('setVolumeFlag4', !volumeFlag);
      if (dropdownFlag) {
        window.tm!.ipcRenderer.send('set-ignore-mouse-events', false);
      }
    };
    const handleMouseLeave = () => {
      console.log('setVolumeFlag5', !volumeFlag);
      if (dropdownFlag) {
        window.tm!.ipcRenderer.send('set-ignore-mouse-events', true, {
          forward: true,
        });
      }
    };
    const barSwitchEnter = () => {
      setBarHidden(false);
      clearTimeout(barHiddenSwitch!);
    };
    const barSwitchLeave = () => {
      barHiddenSwitch = setTimeout(() => {
        setBarHidden(true);
      }, 5000);
    };
    const timerID = setInterval(() => {
      setTime((prevTime) => {
        // 计算下一秒的时分秒
        const newSeconds = prevTime.seconds + 1;
        const newMinutes = Math.floor(newSeconds / 60);
        const newHours = Math.floor(newMinutes / 60);

        return {
          hours: newHours,
          minutes: newMinutes % 60,
          seconds: newSeconds % 60,
        };
      });
    }, 1000);

    window.osn.on('setVolumeClickEvents', (event: any, result: boolean) => {
      setVolumeFlag(result);
      volumeClick();
    });
    window.osn.on('setCameraClickEvents', (event: any, result: boolean) => {
      setCameraFlag(result);
      cameraClick();
    });
    window.osn.on('setRecordClickEvents', (event: any, result: boolean) => {
      setRecordFlag(result);
    });

    barSwitch!.addEventListener('mouseenter', handleMouseEnter);
    barSwitch!.addEventListener('mouseleave', handleMouseLeave);
    el!.addEventListener('mouseenter', barSwitchEnter);
    el!.addEventListener('mouseleave', barSwitchLeave);
    return () => {
      barSwitch!.removeEventListener('mouseenter', handleMouseEnter);
      barSwitch!.removeEventListener('mouseleave', handleMouseLeave);
      el!.removeEventListener('mouseenter', barSwitchEnter);
      el!.removeEventListener('mouseleave', barSwitchLeave);
      // 清除计时器
      clearInterval(timerID);
    };
  }, []);

  const volumeClick = async () => {
    if (getVolumeFlag()) {
      setVolumeFlag(false);
    } else {
      setVolumeFlag(true);
    }
  };
  const cameraClick = async () => {
    if (getCameraFlag()) {
      setCameraFlag(false);
    } else {
      setCameraFlag(true);
    }
  };
  const whiteboard = () => {
    window.tm!.ipcRenderer.send('open-whiteboard-events');
  };

  const stopShare = () => {
    //停止共享前判断是否结束录制
    if (getRecordFlag()) {
      window.tm!.ipcRenderer.send('set-recordClick-events', !getRecordFlag());
    }
    //通知会议页面停止共享，切换回音视频推流，并关闭当前操作栏
    window.tm!.ipcRenderer.send('close-shareOperationBarWindow');
  };

  return (
    <>
      <div
        className={styles.barContent}
        style={barHidden ? { height: 20 } : { height: 70 }}
        id={'barSwitchId'}
      >
        <div className={styles.barTop} hidden={barHidden}>
          <Dropdown.Button
            size={'large'}
            style={{ marginLeft: 20, marginRight: 10 }}
            className={styles.audioButton}
            icon={<DownOutlined />}
            autoAdjustOverflow={false}
            menu={{
              items: volumeList,
              onClick: (item) => {
                window.tm!.ipcRenderer.send(
                  'set-toggle-events',
                  item.key,
                  '',
                  'audio',
                );
              },
              onMouseEnter: () => {
                dropdownFlag = false;
                window.tm!.ipcRenderer.send('set-ignore-mouse-events', false);
              },
              onMouseLeave: () => {
                dropdownFlag = true;
                window.tm!.ipcRenderer.send('set-ignore-mouse-events', true, {
                  forward: true,
                });
              },
            }}
            placement={'bottom'}
            onClick={() => {
              setVolumeFlag(!volumeFlag);
              window.tm!.ipcRenderer.send(
                'set-volumeClick-events',
                !volumeFlag,
              );
            }}
          >
            {volumeFlag && <AudioOutlined />}
            {volumeFlag && '静音'}
            {!volumeFlag && <AudioMutedOutlined />}
            {!volumeFlag && '解除静音'}
          </Dropdown.Button>
          <Dropdown.Button
            style={{ overflow: 'visible', marginRight: 10 }}
            size={'large'}
            icon={<DownOutlined />}
            autoAdjustOverflow={false}
            menu={{
              items: cameraList,
              onClick: (item) => {
                window.tm!.ipcRenderer.send(
                  'set-toggle-events',
                  '',
                  item.key,
                  'camera',
                );
              },
              onMouseEnter: () => {
                dropdownFlag = false;
                window.tm!.ipcRenderer.send('set-ignore-mouse-events', false);
              },
              onMouseLeave: () => {
                dropdownFlag = true;
                window.tm!.ipcRenderer.send('set-ignore-mouse-events', true, {
                  forward: true,
                });
              },
            }}
            placement={'bottom'}
            onClick={() => {
              setCameraFlag(!cameraFlag);
              window.tm!.ipcRenderer.send(
                'set-cameraClick-events',
                !cameraFlag,
              );
            }}
          >
            {cameraFlag && <VideoCameraAddOutlined />}
            {cameraFlag && '开摄像头'}
            {!cameraFlag && <VideoCameraOutlined />}
            {!cameraFlag && '关摄像头'}
          </Dropdown.Button>
          <Button
            icon={<MessageOutlined />}
            style={{ marginRight: 10 }}
            size={'large'}
            onClick={() => {
              window.tm!.ipcRenderer.send('set-chatShow-events');
            }}
          >
            聊天
          </Button>
          <Button
            style={{ marginRight: 10 }}
            icon={<UsergroupAddOutlined />}
            size={'large'}
            onClick={() => {
              window.tm!.ipcRenderer.send('set-inviteUserShow-events');
            }}
          >
            邀请
          </Button>
          <Button
            style={{ marginRight: 10 }}
            icon={<EditOutlined />}
            size={'large'}
            onClick={() => {
              whiteboard();
            }}
          >
            标注
          </Button>
          <Button
            style={{ marginRight: 20 }}
            icon={<Icon component={recordIcon} />}
            size={'large'}
            onClick={() => {
              console.log('getRecordFlag----', getRecordFlag());
              console.log('!getRecordFlag----', !getRecordFlag());
              window.tm!.ipcRenderer.send(
                'set-recordClick-events',
                !getRecordFlag(),
              );
              setRecordFlag(!getRecordFlag());
            }}
          >
            {!getRecordFlag() && '录制'}
            {getRecordFlag() && '结束录制'}
          </Button>
        </div>
        <div className={styles.barMid} id={'barShowId'}>
          <div className={styles.midLeft}>
            共享中&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
            {String(time.hours).padStart(2, '0')}:
            {String(time.minutes).padStart(2, '0')}:
            {String(time.seconds).padStart(2, '0')}{' '}
          </div>
          <div
            className={styles.midRight}
            onClick={() => {
              stopShare();
            }}
          >
            结束共享
          </div>
        </div>
      </div>
      <div id={'barHiddenId'} className={styles.barDown}></div>
    </>
  );
};

export default ShareOperationBar;
